<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="患者ID" prop="patientId">
        <el-input
            v-model="queryParams.patientId"
            placeholder="请输入患者ID"
            clearable
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="就诊医院" prop="hospital">
        <el-input
            v-model="queryParams.hospital"
            placeholder="请输入就诊医院"
            clearable
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="医院地址" prop="hospitalAddress">
        <el-input
            v-model="queryParams.hospitalAddress"
            placeholder="请输入医院地址"
            clearable
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="就诊科室" prop="department">
        <el-input
            v-model="queryParams.department"
            placeholder="请输入就诊科室"
            clearable
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="接诊医生ID" prop="doctorId">
        <el-input
            v-model="queryParams.doctorId"
            placeholder="请输入接诊医生ID"
            clearable
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="医生职称" prop="doctorTitle">
        <el-input
            v-model="queryParams.doctorTitle"
            placeholder="请输入医生职称"
            clearable
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="门诊时间" prop="visitDate">
        <el-date-picker clearable
                        v-model="queryParams.visitDate"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择门诊时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="候诊时间" prop="visitTime">
        <el-date-picker clearable
                        v-model="queryParams.visitTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择候诊时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="挂号费" prop="bookingFee">
        <el-input
            v-model="queryParams.bookingFee"
            placeholder="请输入挂号费"
            clearable
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="预约时间" prop="bookingTime">
        <el-date-picker clearable
                        v-model="queryParams.bookingTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择预约时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="取消原因" prop="cancelReason">
        <el-input
            v-model="queryParams.cancelReason"
            placeholder="请输入取消原因"
            clearable
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="取消时间" prop="cancelTime">
        <el-date-picker clearable
                        v-model="queryParams.cancelTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择取消时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['system:appointments:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['system:appointments:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:appointments:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['system:appointments:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="appointmentsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="预约ID" align="center" prop="id"/>
      <el-table-column label="患者" align="center" prop="patientId"/>
      <el-table-column label="就诊医院" align="center" prop="hospital"/>
      <el-table-column label="医院地址" align="center" prop="hospitalAddress"/>
      <el-table-column label="就诊科室" align="center" prop="department"/>
      <el-table-column label="接诊医生ID" align="center" prop="doctorId"/>
      <el-table-column label="医生职称" align="center" prop="doctorTitle"/>
<!--      <el-table-column label="挂号类型" align="center" prop="bookingType"/>-->
      <el-table-column label="访问日期" align="center" prop="visitDate" width="180">
        <template #default="scope">
      <span v-if="scope?.row?.visitDate">
        {{ parseTime(scope.row.visitDate, '{y}-{m}-{d}') }}
      </span>
          <span v-else>--</span>
        </template>
      </el-table-column>

      <el-table-column label="候诊时间" align="center" prop="visitTime" width="180">
        <template #default="scope">
      <span v-if="scope?.row?.visitTime">
        {{ parseTime(scope.row.visitTime, '{y}-{m}-{d}') }}
      </span>
          <span v-else>--</span>
        </template>
      </el-table-column>

      <el-table-column label="挂号费" align="center" prop="bookingFee"/>

      <el-table-column label="预约时间" align="center" prop="bookingTime" width="180">
        <template #default="scope">
      <span v-if="scope?.row?.bookingTime">
        {{ parseTime(scope.row.bookingTime, '{y}-{m}-{d}') }}
      </span>
          <span v-else>--</span>
        </template>
      </el-table-column>

      <el-table-column label="就诊状态" align="center" prop="status"/>

      <el-table-column label="取消原因" align="center" prop="cancelReason"/>

      <el-table-column label="取消时间" align="center" prop="cancelTime" width="180">
        <template #default="scope">
      <span v-if="scope?.row?.cancelTime">
        {{ parseTime(scope.row.cancelTime, '{y}-{m}-{d}') }}
      </span>
          <span v-else>--</span>
        </template>
      </el-table-column>

      <el-table-column label="挂号备注" align="center" prop="remark"/>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
              size="mini"
              type="text"
              icon="Edit"
              @click="() => handleUpdate(scope.row)"
              v-hasPermi="['system:appointments:edit']"
          >修改
          </el-button>
          <el-button
              size="mini"
              type="text"
              icon="Delete"
              @click="() => handleDelete(scope.row)"
              v-hasPermi="['system:appointments:remove']"
          >删除
          </el-button>
          <el-button
              size="mini"
              type="text"
              icon="View"
              @click="() => handleDetail(scope.row)"
          >详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改预约信息对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="患者姓名" prop="patientId">
          <el-select v-model="form.patientId" placeholder="请选择患者" clearable :style="{width: '100%'}">
            <el-option v-for="(item, index) in patientsList" :key="index" :value="item.id"
                       :label="item.name"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="就诊医院" prop="hospital">
          <!--          <el-input v-model="form.hospital" placeholder="请输入就诊医院"/>-->
          <el-select v-model="form.hospital" placeholder="请选择医院" clearable :style="{width: '100%'}">
            <el-option v-for="(item, index) in hospitalsList" :key="index" :value="item.campusName"
                       :label="item.campusName"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="医院地址" prop="hospitalAddress">
          <el-input v-model="form.hospitalAddress" placeholder="请输入医院地址" disabled/>
        </el-form-item>
        <el-form-item label="就诊科室" prop="department" >
<!--          <el-input v-model="form.department" placeholder="请输入就诊科室"/>-->
          <el-select v-model="form.department" placeholder="请输入就诊科室" clearable :style="{width: '100%'}" :disabled="!form.hospital">
            <el-option v-for="(item, index) in departmentList" :key="index" :value="item.departmentName"
                       :label="item.departmentName"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="接诊医生" prop="doctorId">
          <!--          <el-input v-model="form.doctorId" placeholder="请输入接诊医生ID" />-->
          <el-select v-model="form.doctorId" placeholder="请选择医生" clearable :style="{width: '100%'}" :disabled="!form.department">
            <el-option v-for="(item,index) in doctorList" :key="index" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="医生职称" prop="doctorTitle">
          <el-input v-model="form.doctorTitle" placeholder="请输入医生职称" disabled/>
        </el-form-item>
        <el-form-item label="门诊时间" prop="visitDate">
          <el-date-picker clearable
                          v-model="form.visitDate"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择门诊时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="候诊时间" prop="visitTime">
          <el-date-picker clearable
                          v-model="form.visitTime"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择候诊时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="挂号费" prop="bookingFee">
          <el-input v-model="form.bookingFee" placeholder="请输入挂号费" disabled/>
        </el-form-item>
        <el-form-item label="预约时间" prop="bookingTime">
          <el-date-picker clearable
                          v-model="form.bookingTime"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择预约时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="取消原因" prop="cancelReason">
          <el-input v-model="form.cancelReason" placeholder="请输入取消原因"/>
        </el-form-item>
        <el-form-item label="取消时间" prop="cancelTime">
          <el-date-picker clearable
                          v-model="form.cancelTime"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择取消时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="挂号备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入挂号备注"/>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
                v-for="(item, index) in statuslist"
                :key="index"
                :label="item.label"
            >{{ item.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </template>
    </el-dialog>

    <el-dialog title="预约详情" v-model="detailOpen" width="700px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="患者ID">{{ detailData.patientId }}</el-descriptions-item>
        <el-descriptions-item label="就诊医院">{{ detailData.hospital }}</el-descriptions-item>
        <el-descriptions-item label="医院地址">{{ detailData.hospitalAddress }}</el-descriptions-item>
        <el-descriptions-item label="就诊科室">{{ detailData.department }}</el-descriptions-item>
        <el-descriptions-item label="接诊医生ID">{{ detailData.doctorId }}</el-descriptions-item>
        <el-descriptions-item label="医生职称">{{ detailData.doctorTitle }}</el-descriptions-item>
        <el-descriptions-item label="挂号类型">{{ detailData.bookingType }}</el-descriptions-item>
        <el-descriptions-item label="门诊时间">{{ detailData.visitDate }}</el-descriptions-item>
        <el-descriptions-item label="候诊时间">{{ detailData.visitTime }}</el-descriptions-item>
        <el-descriptions-item label="挂号费">{{ detailData.bookingFee }}</el-descriptions-item>
        <el-descriptions-item label="预约时间">{{ detailData.bookingTime }}</el-descriptions-item>
        <el-descriptions-item label="就诊状态">{{ detailData.status }}</el-descriptions-item>
        <el-descriptions-item label="取消原因">{{ detailData.cancelReason }}</el-descriptions-item>
        <el-descriptions-item label="取消时间">{{ detailData.cancelTime }}</el-descriptions-item>
        <el-descriptions-item label="挂号备注">{{ detailData.remark }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="detailOpen = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {
  listAppointments,
  getAppointments,
  delAppointments,
  addAppointments,
  updateAppointments
} from "@/api/system/appointments"
import {listDoctors} from "@/api/system/doctors.js"
import {listCampus} from "@/api/system/hospitalCampus.js"
import {getDepartmentsByhospitalArea} from "@/api/system/departments.js"
import { listPatients,getPatients } from "@/api/system/patients.js"

export default {
  name: "Appointments",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 预约信息表格数据
      appointmentsList: [],
      //医院列表
      hospitalsList: [],
      //部门列表
      departmentList: [],
      // 弹出层标题
      title: "",
      //所有医生列表
      doctorsList: [],
      // 某一科室医生列表
      doctorList: [],
      //所有患者信息
      patientsList: [],
      // 是否显示弹出层
      open: false,
      // 新增
      detailOpen: false,
      detailData: {},
      a:{
        pageNum: 1,
        pageSize: 100
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        patientId: null,
        hospital: null,
        hospitalAddress: null,
        department: null,
        doctorId: null,
        doctorTitle: null,
        bookingType: null,
        visitDate: null,
        visitTime: null,
        bookingFee: null,
        bookingTime: null,
        status: null,
        cancelReason: null,
        cancelTime: null,
      },
      statuslist: [
        {
          value: "0",
          label: "待就诊"
        },
        {
          value: "1",
          label: "已完成"
        },
        {
          value: "2",
          label: "取消"
        }
      ],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        patientId: [
          {required: true, message: "患者ID不能为空", trigger: "blur"}
        ],
        hospital: [
          {required: true, message: "就诊医院不能为空", trigger: "blur"}
        ],
      }
    }
  },
  created() {
    this.getList()
    this.getPatientsList
  },
  watch: {
    'form.doctorId': {
      handler(newVal) {
        if (newVal) {
          // 根据选中的医生ID查找对应的医生信息
          const selectedDoctor = this.doctorsList.find(doctor => doctor.id === newVal);
          if (selectedDoctor) {
            // 自动填充医生职称
            this.form.doctorTitle = selectedDoctor.title;
            this.form.bookingFee = selectedDoctor.bookingFee;
            // 如果需要，还可以填充其他相关信息
          }
        } else {
          this.form.doctorTitle = ''; // 清空职称
        }
      },
      immediate: true // 是否在初始化时立即执行
    },
    'form.hospital': {
      handler(newVal) {
        if (newVal) {
          // 根据选中的医院名称查找对应的医院信息
          const selectedHospital = this.hospitalsList.find(hospital => hospital.campusName === newVal);
          if (selectedHospital) {
            // 自动填充医院地址
            this.form.hospitalAddress = selectedHospital.address;
            // 如果需要，还可以填充其他相关信息
            getDepartmentsByhospitalArea(selectedHospital.campusName).then(response => {
              this.departmentList = response;
            })
          }
        } else {
          this.form.hospitalAddress = ''; // 清空
        }
      }
    },
    'form.department': {
      async handler(newVal) {
        if (newVal) {
          this.doctorList = this.doctorsList.filter(item => item.department === newVal);
          console.log(this.doctorList)
        }
      }
    },
  },
  methods: {
    getList() {
      this.loading = true
      listAppointments(this.queryParams).then(async response => {
        this.appointmentsList = response.rows
        for (var i = 0; i < this.appointmentsList.length; i++) {
          this.appointmentsList[i].patientId = (await getPatients(this.appointmentsList[i].patientId)).data.name
        }
        this.total = response.total
        this.loading = false
        console.log(response.rows)
      })
      listDoctors().then(response => {
        this.doctorsList = response.rows
        listCampus(this.a).then(response => {
          this.hospitalsList = response.data
        })
      })
      listPatients().then(response => {
        this.patientsList = response.rows
        console.log(response.rows)
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        patientId: null,
        hospital: null,
        hospitalAddress: null,
        department: null,
        doctorId: null,
        doctorTitle: null,
        bookingType: null,
        visitDate: null,
        visitTime: null,
        bookingFee: null,
        bookingTime: null,
        status: null,
        cancelReason: null,
        cancelTime: null,
        remark: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加预约信息"
      console.log('handleAdd 被调用')
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getAppointments(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改预约信息"
      })
    },
    /** 提交按钮 */
    submitForm() {
      console.log(this.form)
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateAppointments(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addAppointments(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除预约信息编号为"' + ids + '"的数据项？').then(function () {
        return delAppointments(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/appointments/export', {
        ...this.queryParams
      }, `appointments_${new Date().getTime()}.xlsx`)
    },
    handleDetail(row) {
      getAppointments(row.id).then(response => {
        this.detailData = response.data
        this.detailOpen = true
      })
    },
  }
}
</script>
